﻿using SLClient;
using SLClient.Extension;
using SLClient.Infrastructure;
using SLClient.ServiceAPI;
using System;
using System.IO.IsolatedStorage;
using System.Linq.Expressions;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Input;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace SLClient.ViewModels
{
    public class LoginViewModel : ViewModelBase
    {
        private Visibility _inStallVisiblity;
        private bool _isEnable;
        private string _loginStatus;
        private Visibility _loginVisibity;
        private Visibility _operationVisibilty;
        private string _passWord;
        private Visibility _processVisibity;
        private string _showText;
        private readonly UserAgreeWindow _userAgreeWindow;
        private string _userName;

        public LoginViewModel(ref UserAgreeWindow userAgreeWindow)
        {
            this._userAgreeWindow = userAgreeWindow;
            this.InitCompents();
            this.CommandInit();
        }

        public void CommandInit()
        {
            RelayCommand command = new RelayCommand(this.Setup)
            {
                IsEnabled = true
            };
            this.SetupCommand = command;
            RelayCommand command2 = new RelayCommand(this.LoginProcess)
            {
                IsEnabled = true
            };
            this.LoginCommand = command2;
        }

        private void TestError(object o, CheckAndDownloadUpdateCompletedEventArgs e)
        {
            if (e.UpdateAvailable)
            {
                this.ProcessVisibity = Visibility.Collapsed;
            }
            if (e.Error != null)
            {
                App.Show("更新发生错误，请尝试从网站上重新安装!");
            }
        }


        public void InitCompents()
        {
            CheckAndDownloadUpdateCompletedEventHandler handler = null;
            if (!(Application.Current.IsRunningOutOfBrowser || (Application.Current.InstallState != 0)))
            {
                this._showText = "请点击下方按钮将\"领先\"程序安装到您的电脑\"开始菜单\"或\"桌面\"上";
            }
            else
            {
                this._showText = "\"领先\"已经安装到您的电脑中,请从\"开始\"菜单或桌面运行!\r\n如果需要卸载重装请点击鼠标右键";
                this._operationVisibilty = Visibility.Collapsed;
            }
            if (Application.Current.IsRunningOutOfBrowser && NetworkInterface.GetIsNetworkAvailable())
            {
                this._inStallVisiblity = Visibility.Collapsed;
                this._loginVisibity = Visibility.Visible;
                this._processVisibity = Visibility.Visible;
                this._loginStatus = "正在检查更新";
                if (handler == null)
                {
                    handler = new CheckAndDownloadUpdateCompletedEventHandler(TestError);
                }
                Application.Current.CheckAndDownloadUpdateCompleted += new CheckAndDownloadUpdateCompletedEventHandler(handler);
                Application.Current.CheckAndDownloadUpdateAsync();
            }
            else
            {
                this._inStallVisiblity = Visibility.Visible;
                this._loginVisibity = Visibility.Collapsed;
            }
            this._processVisibity = Visibility.Collapsed;
            this._isEnable = true;
        }

        public void InitUserScale()
        {
            ServiceClient serviceClient = WCFServicesUtil<ServiceClient>.GetInstance(ServiceType.ServiceAPI);
            serviceClient.GetUserScaleInfosByIdCompleted += delegate(object obj, GetUserScaleInfosByIdCompletedEventArgs arg)
            {
                new IsolatedStorageHelper<ObservableCollection<UserScaleInfo>>().CreateSettingsInStorage("UserScaleInfos", arg.Result);
                this._userAgreeWindow.Show();
            };
            serviceClient.GetAllPlayInfoTyiesCompleted += delegate(object obj, GetAllPlayInfoTyiesCompletedEventArgs arg)
            {
                new IsolatedStorageHelper<ObservableCollection<PlayTypeInfo>>().CreateSettingsInStorage("PlayInfos", arg.Result);
                if (!IsolatedStorageHelper<ObservableCollection<UserScaleInfo>>.IsSettingPersisted("UserScaleInfos"))
                {
                    serviceClient.GetUserScaleInfosByIdAsync(ViewDispatcher.LoginUser.UserId);
                }
                else
                {
                    this._userAgreeWindow.Show();
                }
            };
            if (!IsolatedStorageHelper<ObservableCollection<UserScaleInfo>>.IsSettingPersisted("PlayInfos"))
            {
                serviceClient.GetAllPlayInfoTyiesAsync();
            }
            else
            {
                serviceClient.GetUserScaleInfosByIdAsync(ViewDispatcher.LoginUser.UserId);
            }
        }

        public void LoginProcess()
        {
            if (string.IsNullOrEmpty(this.UserName) || string.IsNullOrEmpty(this.PassWord))
            {
                App.Show("用户名和密码不能为空！");
            }
            else
            {
                this.LoginStatus = "开始检测线路";
                this.ProcessVisibity = 0;
                this.ProcessLogin();
            }
        }

        public void ProcessLogin()
        {
            if (IsolatedStorageHelper<ObservableCollection<UserInfo>>.IsSettingPersisted("LoginUser") && (this.UserName != ViewDispatcher.LoginUser.UserAccount))
            {
                IsolatedStorageSettings.ApplicationSettings.Remove("UserScaleInfos");

                //========== 修正by kevin 清除UserBank的信息 start ==============
                IsolatedStorageSettings.ApplicationSettings.Remove("CurrentUserBank");
                //==================== end ======================================
            }
            if (IsolatedStorageHelper<ObservableCollection<DateTime>>.IsSettingPersisted("IsExpried"))
            {
                TimeSpan span = (TimeSpan) (DateTime.Now - ViewDispatcher.IsExpried);
                if (span.TotalHours > 0.5)
                {
                    IsolatedStorageSettings.ApplicationSettings.Clear();
                }
            }
            new IsolatedStorageHelper<DateTime>().CreateSettingsInStorage("IsExpried", DateTime.Now);
            if (NetworkInterface.GetIsNetworkAvailable())
            {
                this.LoginStatus = "开始连接服务器";
                ServiceClient serviceClient = WCFServicesUtil<ServiceClient>.GetInstance(ServiceType.ServiceAPI);
                serviceClient.GetAnnounmentsCompleted += delegate (object obj, GetAnnounmentsCompletedEventArgs arg) {
                    if (arg.Error != null)
                    {
                        App.Show("网络线路发生问题！");
                        this.ProcessVisibity = Visibility.Collapsed;
                        this.IsEnable = true;
                    }
                    else
                    {
                        this.LoginStatus = "开始登录";
                        new IsolatedStorageHelper<ObservableCollection<Announment>>().CreateSettingsInStorage("News", arg.Result);
                        serviceClient.VerifyUserAsync(this.UserName, this.PassWord);
                    }
                };
                serviceClient.GetSiteConfigCompleted += delegate (object obj, GetSiteConfigCompletedEventArgs arg) {
                    if (arg.Result != null)
                    {
                        new IsolatedStorageHelper<SiteConfig>().CreateSettingsInStorage("SiteConfig", arg.Result);
                    }
                };
                serviceClient.UpdateUserInfoCompleted += delegate (object obj, UpdateUserInfoCompletedEventArgs arg) {
                    this.LoginStatus = "开始登录";
                    if (arg.Error != null)
                    {
                        App.Show("登录客户端出现问题");
                        this.ProcessVisibity = Visibility.Collapsed;
                        this.IsEnable = true;
                    }
                    else
                    {
                        this.ProcessVisibity = Visibility.Collapsed;
                        this.IsEnable = true;
                        this.InitUserScale();
                    }
                    if (!IsolatedStorageHelper<ObservableCollection<Announment>>.IsSettingPersisted("SiteConfig"))
                    {
                        serviceClient.GetSiteConfigAsync();
                    }
                };
                serviceClient.VerifyUserCompleted += delegate (object obj, VerifyUserCompletedEventArgs arg) {
                    this.LoginStatus = "开始登录";
                    if (arg.Error != null)
                    {
                        App.Show("连接服务器失败");
                        this.ProcessVisibity = Visibility.Collapsed;
                        this.IsEnable = true;
                    }
                    else if (arg.Result == null)
                    {
                        App.Show("用户名密码错误");
                        this.ProcessVisibity = Visibility.Collapsed;
                        this.IsEnable = true;
                    }
                    else
                    {
                        new IsolatedStorageHelper<UserInfo>().CreateSettingsInStorage("LoginUser", arg.Result);
                        serviceClient.UpdateUserInfoAsync(arg.Result, true);
                    }
                };
                if (!IsolatedStorageHelper<ObservableCollection<Announment>>.IsSettingPersisted("News"))
                {
                    serviceClient.GetAnnounmentsAsync();
                }
                else
                {
                    this.LoginStatus = "开始连接服务器";
                    serviceClient.VerifyUserAsync(this.UserName.Trim(), this.PassWord.Trim());
                }
            }
            else
            {
                App.Show("网络未连接！");
            }
        }

        public void Setup()
        {
            if (Application.Current.InstallState == 0)
            {
                Application.Current.Install();
            }
            else
            {
                App.Show("软件已成功安装到您的电脑中，请从桌面或者开始菜单启动！");
            }
        }

        public Visibility InStallVisiblity
        {
            get
            {
                return this._inStallVisiblity;
            }
            set
            {
                this._inStallVisiblity = value;
                base.Notify<Visibility>(() => this.InStallVisiblity);
                //base.Notify<Visibility>(System.Linq.Expressions.Expression.Lambda<Func<Visibility>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(LoginViewModel)), (MethodInfo)(LoginViewModel.get_InStallVisiblity)), new ParameterExpression[0]));
            }
        }

        public bool IsEnable
        {
            get
            {
                return this._isEnable;
            }
            set
            {
                this._isEnable = value;
                base.Notify<bool>(() => this.IsEnable);
                //base.Notify<bool>(System.Linq.Expressions.Expression.Lambda<Func<bool>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(LoginViewModel)), (MethodInfo)(LoginViewModel.get_IsEnable)), new ParameterExpression[0]));
            }
        }

        public ICommand LoginCommand { get; set; }

        public string LoginStatus
        {
            get
            {
                return this._loginStatus;
            }
            set
            {
                this._loginStatus = value;
                base.Notify<string>(() => this.LoginStatus);
                //base.Notify<string>(System.Linq.Expressions.Expression.Lambda<Func<string>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(LoginViewModel)), (MethodInfo)(LoginViewModel.get_LoginStatus)), new ParameterExpression[0]));
            }
        }

        public Visibility LoginVisibity
        {
            get
            {
                return this._loginVisibity;
            }
            set
            {
                this._loginVisibity = value;
                base.Notify<Visibility>(() => this.LoginVisibity);
                //base.Notify<Visibility>(System.Linq.Expressions.Expression.Lambda<Func<Visibility>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(LoginViewModel)), (MethodInfo)(LoginViewModel.get_LoginVisibity)), new ParameterExpression[0]));
            }
        }

        public Visibility OperationVisibilty
        {
            get
            {
                return this._operationVisibilty;
            }
            set
            {
                this._operationVisibilty = value;
                base.Notify<Visibility>(() => this.OperationVisibilty);
                //base.Notify<Visibility>(System.Linq.Expressions.Expression.Lambda<Func<Visibility>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(LoginViewModel)), (MethodInfo)(LoginViewModel.get_OperationVisibilty)), new ParameterExpression[0]));
            }
        }

        public string PassWord
        {
            get
            {
                return this._passWord;
            }
            set
            {
                this._passWord = value;
                base.Notify<string>(() => this.PassWord);
                //base.Notify<string>(System.Linq.Expressions.Expression.Lambda<Func<string>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(LoginViewModel)), (MethodInfo)(LoginViewModel.get_PassWord)), new ParameterExpression[0]));
            }
        }

        public Visibility ProcessVisibity
        {
            get
            {
                return this._processVisibity;
            }
            set
            {
                this._processVisibity = value;
                base.Notify<Visibility>(() => this.ProcessVisibity);
                //base.Notify<Visibility>(System.Linq.Expressions.Expression.Lambda<Func<Visibility>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(LoginViewModel)), (MethodInfo)(LoginViewModel.get_ProcessVisibity)), new ParameterExpression[0]));
            }
        }

        public ICommand SetupCommand { get; set; }

        public string ShowText
        {
            get
            {
                return this._showText;
            }
            set
            {
                this._showText = value;
                base.Notify<string>(() => this.ShowText);
                //base.Notify<string>(System.Linq.Expressions.Expression.Lambda<Func<string>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(LoginViewModel)), (MethodInfo)(LoginViewModel.get_ShowText)), new ParameterExpression[0]));
            }
        }

        public string UserName
        {
            get
            {
                return this._userName;
            }
            set
            {
                this._userName = value;
                base.Notify<string>(() => this.UserName);
                //base.Notify<string>(System.Linq.Expressions.Expression.Lambda<Func<string>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(LoginViewModel)), (MethodInfo)(LoginViewModel.get_UserName)), new ParameterExpression[0]));
            }
        }
    }
}

